import React from 'react';
import {
  Box,
  Container,
  Typography,
  Paper,
  Chip,
  Avatar,
  IconButton,
  Divider,
  Button,
  useTheme
} from '@mui/material';
import {
  Favorite as FavoriteIcon,
  FavoriteBorder as FavoriteBorderIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Visibility as VisibilityIcon
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useNavigate, useParams } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { RootState } from '../../store';
import { useGetArticleQuery, useDeleteArticleMutation, useLikeArticleMutation } from '../../store/services/articles';
import Loading from '../../components/common/Loading';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

const ArticleDetail: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const theme = useTheme();
  const { id } = useParams<{ id: string }>();
  const { user } = useSelector((state: RootState) => state.auth);

  const { data: response, isLoading, error } = useGetArticleQuery(Number(id));
  const [deleteArticle] = useDeleteArticleMutation();
  const [likeArticle] = useLikeArticleMutation();

  const article = response?.data;

  const handleDelete = async () => {
    if (window.confirm(t('article.delete.confirm'))) {
      try {
        await deleteArticle(Number(id)).unwrap();
        navigate('/articles');
      } catch (err) {
        console.error('Delete article failed:', err);
      }
    }
  };

  const handleLike = async () => {
    if (!user) {
      navigate('/login');
      return;
    }

    try {
      await likeArticle(Number(id)).unwrap();
    } catch (err) {
      console.error('Like article failed:', err);
    }
  };

  if (isLoading) {
    return <Loading />;
  }

  if (error || !article) {
    return (
      <Box sx={{ p: 3, textAlign: 'center' }}>
        <Typography color="error">
          {t('common.error')}
        </Typography>
      </Box>
    );
  }

  return (
    <Container maxWidth="lg">
      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        {/* 文章标题和操作按钮 */}
        <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
          <Typography variant="h4" component="h1">
            {article.title}
          </Typography>
          <Box>
            {(user?.role === 'ADMIN' || user?.id === article.author.id) && (
              <>
                <IconButton
                  onClick={() => navigate(`/articles/edit/${id}`)}
                  color="primary"
                >
                  <EditIcon />
                </IconButton>
                <IconButton onClick={handleDelete} color="error">
                  <DeleteIcon />
                </IconButton>
              </>
            )}
          </Box>
        </Box>

        {/* 文章元信息 */}
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 3, gap: 2 }}>
          <Avatar
            src={article.author.avatar}
            alt={article.author.username}
            sx={{ width: 40, height: 40 }}
          >
            {article.author.username.charAt(0).toUpperCase()}
          </Avatar>
          <Box>
            <Typography variant="subtitle1">
              {article.author.username}
            </Typography>
            <Typography variant="caption" color="text.secondary">
              {new Date(article.createdAt).toLocaleDateString()}
            </Typography>
          </Box>
        </Box>

        {/* 分类和标签 */}
        <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', mb: 3 }}>
          <Chip
            label={article.category.name}
            color="primary"
            onClick={() => navigate(`/articles?category=${article.category.id}`)}
          />
          {article.tags.map((tag) => (
            <Chip
              key={tag.id}
              label={tag.name}
              variant="outlined"
              onClick={() => navigate(`/articles?tag=${tag.id}`)}
            />
          ))}
        </Box>

        {/* 文章统计信息 */}
        <Box
          sx={{
            display: 'flex',
            gap: 3,
            mb: 3,
            color: 'text.secondary'
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <VisibilityIcon fontSize="small" />
            <Typography variant="body2">
              {article.viewCount}
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Button
              startIcon={article.isLiked ? <FavoriteIcon /> : <FavoriteBorderIcon />}
              onClick={handleLike}
              color={article.isLiked ? 'error' : 'inherit'}
              size="small"
            >
              {article.likeCount}
            </Button>
          </Box>
        </Box>

        <Divider sx={{ my: 3 }} />

        {/* 文章内容 */}
        <Box sx={{ mb: 4 }}>
          {article.cover && (
            <Box
              component="img"
              src={article.cover}
              alt={article.title}
              sx={{
                width: '100%',
                maxHeight: 400,
                objectFit: 'cover',
                borderRadius: 1,
                mb: 3
              }}
            />
          )}
          <Box sx={{ typography: 'body1' }}>
            <ReactMarkdown remarkPlugins={[remarkGfm]}>
              {article.content}
            </ReactMarkdown>
          </Box>
        </Box>

        {/* TODO: 添加评论区 */}
      </Paper>
    </Container>
  );
};

export default ArticleDetail; 